"""
公告相关模型

发布当前站点公告信息
"""
from django.db import models
from django.utils import timezone
from account.models import Account


# Create your models here.

class AnnouncementBase(models.Model):
    """
    公告表
    """
    publish_time = models.DateTimeField(default=timezone.now, verbose_name='发布时间')
    user = models.ForeignKey(Account, verbose_name='公告发布人', on_delete=models.CASCADE)
    title = models.CharField(verbose_name='公告标题', max_length=50)
    content = models.TextField(verbose_name='公告内容')
    status = models.IntegerField(default=0, verbose_name='状态0审核1审核通过2审核不通过')

    def __str__(self):
        return self.title

    class Meta:
        """
        重命名
        """
        abstract = True
        # db_table = 'announcement_announcement'


# class Announcement0(AnnouncementBase):
#     class Meta:
#         """
#         重命名
#         """
#         db_table = 'announcement_announcement_0'
#
#
# class Announcement1(AnnouncementBase):
#     class Meta:
#         """
#         重命名
#         """
#         db_table = 'announcement_announcement_1'
#
#
# class Announcement2(AnnouncementBase):
#     class Meta:
#         """
#         重命名
#         """
#         db_table = 'announcement_announcement_2'
#

SHARD_TABLE_NUM = 3


class Announcement(models.Model):
    @classmethod
    def get_student_db_model(cls, user_id=None):
        suffix = user_id % SHARD_TABLE_NUM
        table_name = 'announcement_announcement_%s' % suffix
        # construct a private field _user_model_dict to store the model,
        # it can help to accelerate the speed of get model
        if table_name in cls._announcement_db_model:
            return cls._announcement_db_model[table_name]

        class Meta:
            db_table = table_name

        attrs = {
            '__module__': cls.__module__,
            'Meta': Meta
        }
        # the first param is obejct name
        # second: class
        # the class field info
        announcement_db_model = type(str('Announcement%s') % suffix, (cls,), attrs)
        cls._announcement_db_model[table_name] = announcement_db_model
        return announcement_db_model

    _announcement_db_model = {}  # help to reuse the model object
    publish_time = models.DateTimeField(default=timezone.now, verbose_name='发布时间')
    user = models.ForeignKey(Account, verbose_name='公告发布人', on_delete=models.CASCADE)
    title = models.CharField(verbose_name='公告标题', max_length=50)
    content = models.TextField(verbose_name='公告内容')
    status = models.IntegerField(default=0, verbose_name='状态0审核1审核通过2审核不通过')

    class Meta:
        abstract = True
